package com.alinesno.cloud.common.web.login.auth;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.common.web.login.session.CurrentAccountSession;

/**
 * 用户操作权限判断，用户操作权限包含两部分，逻辑判断由<br/>
 * 操作权限: 判断是否存在操作(操作权限)和菜单(菜单权限)
 * 
 * @author LuoAnDong
 * @since 2019年4月8日 下午8:30:43
 */
@Order(5)
@Aspect
@Component
public class OperationPermissionsAspect {

	private static final Logger log = LoggerFactory.getLogger(OperationPermissionsAspect.class);

	@Pointcut("@annotation(com.alinesno.cloud.common.web.login.auth.OperationPermissions)")
	public void pointcut() {
	}

	@Around("pointcut()")
	public Object around(ProceedingJoinPoint point) {
		Object result = null;

		try {
			// 权限判断 
			isPermitted(point);
			// 执行方法
			result = point.proceed();
		} catch (UnauthorizedOperationException e) {
			log.error("用户没有操作权限异常:{}", e);
			throw new UnauthorizedOperationException("用户没有操作权限.");
		} catch (Throwable e) {
			log.error("用户权限异常:{}", e);
		}

		return result;
	}

	/**
	 * 判断用户是否有操作权限
	 * 
	 * @param joinPoint
	 * @param time
	 */
	private void isPermitted(ProceedingJoinPoint joinPoint) throws UnauthorizedOperationException {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		ManagerAccountEntity account = CurrentAccountSession.get(request);
		String url = request.getRequestURL().toString();

		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		OperationPermissions operationPermissions = method.getAnnotation(OperationPermissions.class);
		
		log.debug("请求链接:{}" , url);
		
		if(operationPermissions != null) { // 操作权限判断
			
			String[] permission = operationPermissions.value();
			log.debug("permission:{} , url:{} , account:{}", JSON.toJSONString(permission), url, JSON.toJSONString(account));
			
		} else { // 请求链接权限判断
			
		}
	}

}
